<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="入库单编号" prop="recptCode">
        <el-input v-model="queryParams.recptCode" placeholder="请输入入库单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="入库单名称" prop="recptName">
        <el-input v-model="queryParams.recptName" placeholder="请输入入库单名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商名称" prop="vendorName">
        <el-input v-model="queryParams.vendorName" placeholder="请输入供应商名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="单据状态" prop="status">
        <el-select v-model="queryParams.status" class="no-select-color"   placeholder="请选择单据状态">
          <el-option v-for="dict in dict.type.mes_order_status" :key="dict.value" :label="dict.label"
                     :value="dict.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="订单编号" prop="poCode">
        <el-input v-model="queryParams.poCode" placeholder="请输入订单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="入库日期" prop="recptDate">
        <el-date-picker clearable v-model="queryParams.recptDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择入库日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:wm:itemrecpt:add','mes:wm:itemrecpt:input','mes:wm:itemrecpt:base:edit']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:wm:itemrecpt:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:wm:itemrecpt:remove','mes:wm:itemrecpt:input','mes:wm:itemrecpt:base:edit']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['mes:wm:itemrecpt:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemrecptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单编号" align="center" width="180px" prop="recptCode">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)" v-hasPermi="['mes:wm:itemrecpt:query']">{{
            scope.row.recptCode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="入库单名称" align="center" prop="recptName" :show-overflow-tooltip="true" />
      <el-table-column label="供应商名称" align="center" prop="vendorName" :show-overflow-tooltip="true" />
      <el-table-column label="入库日期" align="center" prop="recptDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购订单号" align="center" prop="poCode" />
      <el-table-column label="单据总额" align="center" prop="totalAmount" />
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-video-play" v-if="scope.row.status == 'PREPARE'"
                     @click="handleExecute(scope.row)" v-hasPermi="['mes:wm:itemrecpt:excute']">执行入库</el-button>

          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.status == 'PREPARE'"
            @click="handleUpdate(scope.row)" v-hasPermi="['mes:wm:itemrecpt:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" v-if="scope.row.status == 'PREPARE'"
            @click="handleDelete(scope.row)" v-hasPermi="['mes:wm:itemrecpt:remove','mes:wm:itemrecpt:input','mes:wm:itemrecpt:base:edit']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改物料入库单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库单编号" prop="recptCode">
              <el-input v-model="form.recptCode" placeholder="请输入入库单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag" active-color="#13ce66" active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view' && form.status == 'PREPARE'">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库单名称" prop="recptName">
              <el-input v-model="form.recptName" placeholder="请输入入库单名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库日期" prop="recptDate">
              <el-date-picker clearable v-model="form.recptDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择入库日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购订单号" prop="poCode">
              <el-input v-model="form.poCode" placeholder="请输入采购订单号" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="form.status" class="no-select-color" disabled placeholder="请选择单据状态">
                <el-option v-for="dict in dict.type.mes_order_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总金额" prop="linkType">
              <el-tooltip effect="dark" placement="right">
                <div slot="content">
                  总金额会通过计算得到，无法手动修改
                </div>
                <el-input :value="calculatedTotalAmount" readonly="readonly">
                </el-input>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 物料信息表格 -->
      <el-divider content-position="center">物料信息</el-divider>
      <el-card shadow="always" class="box-card">
        <div slot="header">
        
<!--           <div style="float: right;">
            <el-button v-if="optType != 'view' && form.status == 'PREPARE'"
                       style="padding: 3px 0; margin-right: 10px;"
                       icon="el-icon-delete"
                       @click="handleBatchDeleteLine"
                      type="danger" plain
                       size="mini"
                       :disabled="lineMultiple"
                       v-hasPermi="['mes:wm:itemrecpt:remove','mes:wm:itemrecpt:input','mes:wm:itemrecpt:base:edit']">
              批量删除
            </el-button>
            <el-button v-if="optType != 'view' && form.status == 'PREPARE'"
                       style="padding: 3px 0"
                       type="text"
                       icon="el-icon-plus"
                       @click="handleAddLine"
                       v-hasPermi="['mes:wm:itemrecpt:add','mes:wm:itemrecpt:input','mes:wm:itemrecpt:base:edit']">
              批量添加物料
            </el-button>
          </div> -->

          <div style="margin-bottom: 3px;">
            <el-button v-if="optType != 'view' && form.status == 'PREPARE'"
                       style="padding: 3px 0; margin-right: 10px;"
                      
                       @click="handleBatchDeleteLine"
                       type="danger"
                       size="mini"
                        icon="el-icon-delete"
                       :disabled="lineMultiple"
                       v-hasPermi="['mes:wm:itemrecpt:remove','mes:wm:itemrecpt:input','mes:wm:itemrecpt:base:edit']">
              批量删除
            </el-button>
            <el-button v-if="optType != 'view' && form.status == 'PREPARE'"
                       style="padding: 3px 0"
                       type="primary"
                       icon="el-icon-plus"
                       size="mini"
                       @click="handleAddLine"
                       v-hasPermi="['mes:wm:itemrecpt:add','mes:wm:itemrecpt:input','mes:wm:itemrecpt:base:edit']">
              批量添加物料
            </el-button>

          </div>

        </div>

        <el-table v-loading="lineLoading" :data="itemrecptlineList" @selection-change="handleLineSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="物料编码" align="center" width="120px" prop="itemCode" />
          <el-table-column label="物料名称" align="center" prop="itemName" :show-overflow-tooltip="true" />
          <el-table-column label="单位" align="center" prop="unitOfMeasure" width="80" />
          <el-table-column label="物料图片" align="left" prop="imgUrl" width="80">
            <template slot-scope="scope">
              <image-preview v-if="scope.row.imgUrl" :src="scope.row.imgUrl" :width="50" :height="50"/>
            </template>
          </el-table-column>

          <el-table-column label="供应商名字" width="200" align="center">
            <template slot-scope="scope">
              <el-input 
                v-if="optType != 'view' && form.status == 'PREPARE'"
                v-model="scope.row.vendorName" 
                size="mini"
                readonly
                placeholder="请选择供应商"
              >
                <el-button slot="append" @click="handleSelectVendor(scope.row)" icon="el-icon-search"></el-button>
              </el-input>
              <span v-else>{{ scope.row.vendorName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单据金额" align="center" width="180">
            <template slot-scope="scope">
              <el-input-number 
                v-if="optType != 'view' && form.status == 'PREPARE'"
                v-model="scope.row.amount" 
                :min="0"
                :controls="true"
                :precision="2"
                controls-position=""
                 style="width:160px;"
                @change="handleAmountChange(scope.row)"
              />
              <span v-else>{{ scope.row.amount }}</span>
            </template>
          </el-table-column>

          <el-table-column label="入库数量" align="center" width="180">
            <template slot-scope="scope">
              <el-input-number 
                v-if="optType != 'view' && form.status == 'PREPARE'"
                v-model="scope.row.quantityRecived" 
                :min="0"
                :controls="true"
                :precision="2"
                controls-position=""
                style="width:160px;"
                @change="handleQuantityChange(scope.row)"
              />
              <span v-else>{{ scope.row.quantityRecived }}</span>
            </template>
          </el-table-column>
          <el-table-column label="批次号" align="center" width="120">
            <template slot-scope="scope">
              <div v-if="optType != 'view' && form.status == 'PREPARE'">
                <el-input 
                  v-model="scope.row.batchCode" 
                  size="mini"
                  @blur="handleBatchCodeChange(scope.row)"
                  @focus="handleBatchCodeFocus(scope.row)"
                  style="width: 100px;"
                  :placeholder="generateBatchCode()"
                />
                <div v-if="!scope.row.batchCode" style="font-size: 10px; color: #909399; margin-top: 2px;">
                  默认: {{ generateBatchCode() }}
                </div>
              </div>
              <span v-else>{{ getDisplayBatchCode(scope.row.batchCode) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="仓库" align="center" width="280">
            <template slot-scope="scope">
              <el-cascader 
                v-if="optType != 'view' && form.status == 'PREPARE'"
                v-model="scope.row.warehouseInfo" 
                :options="warehouseOptions" 
                :props="warehouseProps" 
                size="mini"
                @change="handleWarehouseChange(scope.row)"
                style="width: 200px;"
                placeholder="选择"
              />
              <span v-else>{{ scope.row.warehouseName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库区" align="center" prop="locationName" width="180" />
          <el-table-column label="库位" align="center" prop="areaName" width="180" />
          <el-table-column label="有效期" align="center" width="120">
            <template slot-scope="scope">
              <el-date-picker 
                v-if="optType != 'view' && form.status == 'PREPARE'"
                v-model="scope.row.expireDate" 
                type="date" 
                value-format="yyyy-MM-dd"
                size="mini"
                @change="handleExpireDateChange(scope.row)"
                style="width: 100px;"
              />
              <span v-else>{{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
        
      
          <el-table-column label="操作" align="center" width="120px" v-if="optType != 'view'"
            class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateLine(scope.row)"
                         v-hasPermi="['mes:wm:itemrecpt:base:edit','mes:wm:itemrecpt:input']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteLine(scope.row)"
                         v-hasPermi="['mes:wm:itemrecpt:remove','mes:wm:itemrecpt:input','mes:wm:itemrecpt:base:edit']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 批量添加物料选择组件 -->
      <ItemSelect ref="batchItemSelect" @onSelected="onItemSelected"></ItemSelect>
      
      <!-- 供应商选择组件 -->
      <VendorSelect ref="vendorSelect" :itemId="currentEditRow ? currentEditRow.itemId : null" @onSelected="onVendorSelected"></VendorSelect>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType == 'view' || form.status != 'PREPARE'">返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="form.status == 'PREPARE' && optType != 'view'">保
          存00</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 物料创建对话框 -->
    <el-dialog :title="itemCreateTitle" :visible.sync="itemCreateOpen" width="1000px" append-to-body>
      <el-form ref="itemCreateForm" :model="itemCreateForm" :rules="itemCreateRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="itemCode">
              <el-input v-model="itemCreateForm.itemCode" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="itemName">
              <el-input v-model="itemCreateForm.itemName" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="itemCreateForm.specification" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-select v-model="itemCreateForm.unitOfMeasure" placeholder="请选择单位">
                <el-option
                  v-for="unit in unitOptions"
                  :key="unit.unitOfMeasure"
                  :label="unit.unitOfMeasure"
                  :value="unit.unitOfMeasure"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料分类" prop="itemTypeId">
              <el-cascader
                v-model="itemCreateForm.itemTypeId"
                :options="itemTypeOptions"
                :props="itemTypeProps"
                placeholder="请选择物料分类"
                clearable
                @change="handleItemTypeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料/产品" prop="itemOrProduct">
              <el-select v-model="itemCreateForm.itemOrProduct" placeholder="请选择物料/产品">
                <el-option
                  v-for="dict in dict.type.mes_item_product"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="itemCreateForm.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitItemCreate">确 定11</el-button>
        <el-button @click="cancelItemCreate">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addItemrecpt, addAllItemrecpt, delItemrecpt, execute, getItemrecpt, listItemrecpt, updateItemrecpt, updateAllItemrecpt } from "@/api/mes/wm/itemrecpt";
import { addItemrecptline, delItemrecptline, getItemrecptline, listItemrecptline, updateItemrecptline } from "@/api/mes/wm/itemrecptline";
import { getTreeList } from "@/api/mes/wm/warehouse";
import { genCode } from "@/api/system/autocode/rule";
import { addMdItem } from "@/api/mes/md/mdItem";
import { listAllUnitmeasure } from "@/api/mes/md/unitmeasure";
import { treeselect } from "@/api/mes/md/itemtype";
import IqcSelect from "@/components/iqcSelect/single.vue";
import VendorSelect from "@/components/vendorSelect/single.vue";
import ItemSelect from "@/components/itemSelect/item-purchase.vue";
import ImagePreview from "@/components/ImagePreview/index.vue";
export default {
  name: "Itemrecpt",
  dicts: ['mes_order_status', 'sys_yes_no', 'mes_item_product'],
  components: { VendorSelect, IqcSelect, ItemSelect, ImagePreview },
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      warehouseInfo: [],
      warehouseOptions: [],
      warehouseProps: {
        multiple: false,
        value: 'pId',
        label: 'pName',
        checkStrictly: true
      },
      // 遮罩层
      loading: true,
      lineLoading: false,
      // 选中数组
      ids: [],
      lineIds: [],
      delLineIds: [], // 删除非临时明细主键
      // 非单个禁用
      single: true,
      multiple: true,
      lineMultiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      lineTotal: 0,
      // 物料入库单表格数据
      itemrecptList: [],
      itemrecptlineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recptCode: null,
        recptName: null,
        iqcId: null,
        iqcCode: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        recptDate: null,
        poCode: null,
        status: null,
      },
      lineQueryParams: {
        pageNum: 1,
        pageSize: 10,
        recptId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        recptCode: [
          { required: true, message: "入库单编号不能为空", trigger: "blur" }
        ],
        recptName: [
          { required: true, message: "入库单名称不能为空", trigger: "blur" }
        ],
        recptDate: [
          { required: true, message: "入库时间不能为空", trigger: "blur" }
        ],
      },


      // 物料创建相关
      itemCreateOpen: false,
      itemCreateTitle: '',
      itemCreateForm: {
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        itemTypeId: null,
        itemOrProduct: null,
        remark: null,
      },
      itemCreateRules: {
        itemCode: [
          { required: true, message: "物料编码不能为空", trigger: "blur" }
        ],
        itemName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" }
        ],
        unitOfMeasure: [
          { required: true, message: "单位不能为空", trigger: "change" }
        ],
        itemTypeId: [
          { required: true, message: "物料分类不能为空", trigger: "change" }
        ],
        itemOrProduct: [
          { required: true, message: "物料/产品不能为空", trigger: "change" }
        ],
      },
      unitOptions: [],
      itemTypeOptions: [],
      itemTypeProps: {
        multiple: false,
        value: 'itemTypeId',
        label: 'itemTypeName',
        children: 'children',
        checkStrictly: true
      },
      // 当前编辑的行（用于供应商选择）
      currentEditRow: null,
      // 数据修改标记
      dataModified: false,
    };
  },
  created() {
    // 添加全局错误处理
    this.$options.errorHandler = (err, vm, info) => {
      console.error('Vue Error:', err, info);
      // 防止错误传播
      return false;
    };
    
    this.getList();
    this.getWarehouseList();
    this.getUnitList();
    this.getItemTypeList();
  },
  beforeDestroy() {
    // 清理异步操作
    this.currentEditRow = null;
    this.loading = false;
    this.lineLoading = false;
  },
  watch: {
    // 监听明细数据变化，自动更新总金额
    itemrecptlineList: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.updateTotalAmount();
        }
      },
      deep: true
    },

  },
  beforeDestroy() {
    // 设置销毁标记
    this._isDestroyed = true;
    
    // 清理异步操作和状态
    this.loading = false;
    this.lineLoading = false;
    this.currentEditRow = null;
    
    // 清理定时器或其他异步操作
    if (this._asyncOperations) {
      this._asyncOperations.forEach(operation => {
        if (operation && typeof operation.cancel === 'function') {
          operation.cancel();
        }
      });
    }
  },
  mounted() {
    // 修复radio组件的无障碍访问问题
    this.$nextTick(() => {
      this.fixRadioAccessibility();
    });
  },
  updated() {
    // 在组件更新后也修复无障碍访问问题
    this.$nextTick(() => {
      this.fixRadioAccessibility();
    });
  },
  computed: {
    // 计算总金额
    calculatedTotalAmount() {
      try {
        let total = 0;
        this.itemrecptlineList.forEach(item => {
          if (item.amount && !isNaN(item.amount) && parseFloat(item.amount) > 0) {
            total += parseFloat(item.amount);
          }
        });
        return total.toFixed(2);
      } catch (error) {
        return '0.00';
      }
    }
  },

  methods: {
    /** 查询物料入库单列表 */
    getList() {
      this.loading = true;
      const promise = listItemrecpt(this.queryParams);
      
      promise.then(response => {
        if (this.loading && !this._isDestroyed) { // 检查组件是否仍然存在
          this.itemrecptList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      }).catch(error => {
        if (this.loading && !this._isDestroyed) {
          this.loading = false;
          console.error('获取物料入库单列表失败:', error);
        }
      });
      
      // 存储异步操作以便清理
      if (!this._asyncOperations) {
        this._asyncOperations = [];
      }
      this._asyncOperations.push(promise);
    },
    /** 查询物料入库单行列表 */
    getLineList() {
      if (!this.form.recptId) {
        // 如果是新增入库单，显示空的列表
        this.itemrecptlineList = [];
        this.lineTotal = 0;
        this.lineLoading = false;
        // 确保总金额是最新的
        this.updateTotalAmount();
        return;
      }
      this.lineLoading = true;
      this.lineQueryParams.recptId = this.form.recptId;
      const promise = listItemrecptline(this.lineQueryParams);
      
      promise.then(response => {
        if (this.lineLoading && !this._isDestroyed) { // 检查组件是否仍然存在
          this.itemrecptlineList = response.rows;
          this.lineTotal = response.total;
          this.lineLoading = false;
          // 确保总金额是最新的
          this.updateTotalAmount();
          
          // 为每个明细项更新仓库名称和warehouseInfo数组
          this.itemrecptlineList.forEach(item => {
            if (item.warehouseId || item.locationId || item.areaId) {
              this.updateWarehouseNamesForItem(item);
              // 设置warehouseInfo数组用于级联选择器
              item.warehouseInfo = [item.warehouseId, item.locationId, item.areaId].filter(id => id != null);
            } else {
              item.warehouseInfo = [];
            }
          });
        }
      }).catch(error => {
        if (this.lineLoading && !this._isDestroyed) {
          console.error('Error fetching line list:', error);
          this.lineLoading = false;
        }
      });
      
      // 存储异步操作以便清理
      if (!this._asyncOperations) {
        this._asyncOperations = [];
      }
      this._asyncOperations.push(promise);
    },
    getWarehouseList() {
      getTreeList().then(response => {
        if (response.data) {
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode.indexOf('VIR') == -1;
          });;
        }
        this.warehouseOptions.map(w => {
          w.children.map(l => {
            let lstr = JSON.stringify(l.children).replace(/locationId/g, 'lId').replace(/areaId/g, 'pId').replace(/areaName/g, 'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g, 'wId').replace(/locationId/g, 'pId').replace(/locationName/g, 'pName');
          w.children = JSON.parse(wstr);

        });
        let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g, 'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
        
        // 如果已经有明细数据，更新仓库名称和warehouseInfo数组
        if (this.itemrecptlineList && this.itemrecptlineList.length > 0) {
          this.itemrecptlineList.forEach(item => {
            if (item.warehouseId || item.locationId || item.areaId) {
              this.updateWarehouseNamesForItem(item);
              // 设置warehouseInfo数组用于级联选择器
              item.warehouseInfo = [item.warehouseId, item.locationId, item.areaId].filter(id => id != null);
            } else {
              item.warehouseInfo = [];
            }
          });
        }
      });
    },
    getUnitList() {
      listAllUnitmeasure().then(response => {
        this.unitOptions = response.data;
      });
    },
    getItemTypeList() {
      treeselect().then(response => {
        this.itemTypeOptions = response.data;
      }).catch(error => {
        console.error('Error fetching item type tree:', error);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.dataModified = false; // 重置修改标记
      this.reset();
    },

    // 物料创建取消按钮
    cancelItemCreate() {
      this.itemCreateOpen = false;
      this.resetItemCreate();
    },
    // 表单重置
    reset() {
      this.form = {
        recptId: null,
        recptCode: null,
        recptName: null,
        iqcId: null,
        iqcCode: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        recptDate: null,
        poCode: null,
        status: "PREPARE",
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.autoGenFlag = false;
      this.resetForm("form");
      this.itemrecptlineList = [];
      this.lineIds = [];
      this.lineMultiple = true;
      this.delLineIds = [];
      // 确保总金额是最新的
      this.updateTotalAmount();
    },

    // 物料创建表单重置
    resetItemCreate() {
      this.itemCreateForm = {
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        itemTypeId: null,
        itemOrProduct: null,
        remark: null,
      };
      this.resetForm("itemCreateForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recptId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 子项多选框选中数据
    handleLineSelectionChange(selection) {
      this.lineIds = selection.map(item => item.lineId)
      this.lineMultiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.warehouseInfo = [];
      this.open = true;
      this.title = "添加物料入库单";
      this.optType = "add";
      // 新增时显示空的子项表格
      this.getLineList();
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      const recptIds = row.recptId
      getItemrecpt(recptIds).then(response => {
        this.form = response.data;
        this.warehouseInfo[0] = response.data.warehouseId;
        this.warehouseInfo[1] = response.data.locationId;
        this.warehouseInfo[2] = response.data.areaId;
        this.open = true;
        this.title = "查看入库单信息";
        this.optType = "view";
        this.getLineList();
      }).catch(error => {
        console.error('获取入库单详情失败:', error);
        this.$modal.msgError("获取入库单详情失败");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recptId = row.recptId || this.ids
      getItemrecpt(recptId).then(response => {
        this.form = response.data;
        this.warehouseInfo[0] = response.data.warehouseId;
        this.warehouseInfo[1] = response.data.locationId;
        this.warehouseInfo[2] = response.data.areaId;
        this.open = true;
        this.title = "修改物料入库单";
        this.optType = "edit";
        this.getLineList();
      }).catch(error => {
        console.error('获取入库单详情失败:', error);
        this.$modal.msgError("获取入库单详情失败");
      });
    },

    //执行入库
    handleExecute(row) {
      const recptIds = row.recptId || this.ids;
      this.$modal.confirm('确认执行入库？').then(function () {
        return execute(recptIds)//执行入库
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("入库成功");
      }).catch(() => { });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 验证物料明细中的仓库和入库数量不能为空
          if (!this.validateItemDetails()) {
            return;
          }
          
          // 确保数据同步完整性
          this.ensureDataSync();
          
          // 清理表头ID（如果是临时的）
          const header = this.clearHeaderIdIfTemporary(this.form);

          // 清理明细ID（如果是临时的）
          const details = this.itemrecptlineList.map(item => this.clearIdIfTemporary(item));

          // 删除的明细ID
          const delLineIds = this.delLineIds;

          const submitData = {
            header,
            details,
            delLineIds
          };

          console.log('------submitForm -----submitData,', submitData);
                      // 新增入库单
          addAllItemrecpt(submitData).then(response => {
              this.$modal.msgSuccess("保存成功");
              this.open = false;
              this.dataModified = false; // 重置修改标记
              // 更新列表中的数据
              this.updateListData(response.data);
              // 强制刷新列表以确保数据同步
              this.$nextTick(() => {
                this.getList();
              });
            }).catch(error => {
              this.$modal.msgError("保存失败：" + (error.message || "请求异常"));
              console.error("保存入库单失败", error);
            });

        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const recptIds = row.recptId || this.ids;
      this.$modal.confirm('是否确认删除物料入库单？').then(function () {
        return delItemrecpt(recptIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/wm/itemrecpt/export', {
        ...this.queryParams
      }, `itemrecpt_${new Date().getTime()}.xlsx`)
    },
    //选择默认的仓库、库区、库位
    handleWarehouseChanged(obj) {
      if (obj != null) {
        this.form.warehouseId = obj[0];
        this.form.locationId = obj[1];
        this.form.areaId = obj[2];
      }
    },

    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('ITEMRECPT_CODE').then(response => {
          this.form.recptCode = response;
        });
      } else {
        this.form.recptCode = null;
      }
    },

    // 子项相关方法
    /** 新增子项按钮操作 */
    handleAddLine() {
      // 直接打开物料选择对话框进行批量添加
      this.handleSelectProduct();
    },



    /** 删除子项按钮操作 */
    handleDeleteLine(row) {
      const lineIds = row.lineId || this.lineIds;
      this.$modal.confirm('是否确认删除物料明细？').then(() => {
        // 检查是否是临时数据（本地数组中的数据）
        if (typeof lineIds === 'string' && lineIds.startsWith('temp_')) {
          // 从本地数组中删除
          const index = this.itemrecptlineList.findIndex(item => item.lineId === lineIds);
          if (index > -1) {
            this.itemrecptlineList.splice(index, 1);
            this.lineTotal = this.itemrecptlineList.length;
            this.updateTotalAmount();
            this.$modal.msgSuccess("删除成功");
          }
        } else {
          // 将永久ID添加到删除列表中，不立即删除数据库数据
          if (Array.isArray(lineIds)) {
            lineIds.forEach(id => {
              if (!this.isTemporaryId(id) && !this.delLineIds.includes(id)) {
                this.delLineIds.push(id);
              }
            });
          } else {
            if (!this.isTemporaryId(lineIds) && !this.delLineIds.includes(lineIds)) {
              this.delLineIds.push(lineIds);
            }
          }

          // 从本地数组中删除
          if (Array.isArray(lineIds)) {
            lineIds.forEach(id => {
              const index = this.itemrecptlineList.findIndex(item => item.lineId === id);
              if (index > -1) {
                this.itemrecptlineList.splice(index, 1);
              }
            });
          } else {
            const index = this.itemrecptlineList.findIndex(item => item.lineId === lineIds);
            if (index > -1) {
              this.itemrecptlineList.splice(index, 1);
            }
          }

          this.lineTotal = this.itemrecptlineList.length;
          this.updateTotalAmount();
          this.$modal.msgSuccess("删除成功");
        }
      }).catch(() => { });
    },
        /** 批量删除子项按钮操作 */
    handleBatchDeleteLine() {
      if (this.lineIds.length === 0) {
        this.$modal.msgError("请选择要删除的物料明细");
        return;
      }

      this.$modal.confirm(`是否确认删除选中的 ${this.lineIds.length} 条物料明细？`).then(() => {
        const tempIds = [];
        const dbIds = [];

        // 分离临时数据和数据库数据
        this.lineIds.forEach(id => {
          if (this.isTemporaryId(id)) {
            tempIds.push(id);
          } else {
            dbIds.push(id);
          }
        });

        // 删除临时数据
        tempIds.forEach(id => {
          const index = this.itemrecptlineList.findIndex(item => item.lineId === id);
          if (index > -1) {
            this.itemrecptlineList.splice(index, 1);
          }
        });

        // 将永久ID添加到删除列表中，不立即删除数据库数据
        dbIds.forEach(id => {
          if (!this.delLineIds.includes(id)) {
            this.delLineIds.push(id);
          }
        });

        // 从本地数组中删除永久数据
        dbIds.forEach(id => {
          const index = this.itemrecptlineList.findIndex(item => item.lineId === id);
          if (index > -1) {
            this.itemrecptlineList.splice(index, 1);
          }
        });

        // 更新本地数据
        this.lineTotal = this.itemrecptlineList.length;
        this.updateTotalAmount();

        this.$modal.msgSuccess("批量删除成功");
      }).catch(() => { });
    },
    /** 提交子项表单 */


    //物料选择
    handleSelectProduct() {
      // 检查是否在编辑模式下
      if (this.optType === 'view' || this.form.status !== 'PREPARE') {
        this.$modal.msgWarning("当前状态不允许添加物料");
        return;
      }
      
      try {
        // 使用 $nextTick 确保组件已经渲染完成
        this.$nextTick(() => {
          // 检查组件是否仍然存在
          if (!this.$refs) return;
          
          // 优先使用批量添加的 ItemSelect 组件
          if (this.$refs.batchItemSelect) {
            if (typeof this.$refs.batchItemSelect.show === 'function') {
              this.$refs.batchItemSelect.show();
            } else if (this.$refs.batchItemSelect.showFlag !== undefined) {
              this.$refs.batchItemSelect.showFlag = true;
            } else {
              this.$modal.msgWarning("批量添加组件方法不可用");
            }
          } else {
            this.$modal.msgWarning("物料选择组件未找到");
          }
        });
      } catch (error) {
        console.error('Error in handleSelectProduct:', error);
        this.$modal.msgError("打开物料选择对话框时发生错误：" + error.message);
      }
    },
    //物料选择弹出框
    onItemSelected(obj) {
      // 兼容两种格式：数组格式（批量选择）和单个对象格式（单选）
      let items = [];
      if (Array.isArray(obj)) {
        items = obj; // 批量选择，obj 是数组
      } else if (obj != undefined && obj != null) {
        // 批量添加状态 - 转换为数组格式
        items = [obj];
      }

      // 批量添加逻辑
      if (items && items.length > 0) {
        let addedCount = 0;
        let skippedCount = 0;
        
        items.forEach((item, index) => {
          // 检查是否已存在相同的物料
          const existingItem = this.itemrecptlineList.find(line => line.itemId === item.itemId);
          if (existingItem) {
            skippedCount++;
            return; // 跳过已存在的物料
          }
          
          const newLine = {
            lineId: 'temp_' + Date.now() + '_' + index + '_' + Math.random().toString(36).substr(2, 9), // 临时ID
            recptId: this.form.recptId,
            itemId: item.itemId,
            itemCode: item.itemCode,
            itemName: item.itemName,
            unitOfMeasure: item.unitOfMeasure,
            specification: item.specification,
            imgUrl: item.imgUrl,
            quantityRecived: 1, // 默认数量为1
            amount: 0, // 默认金额为0
            batchCode: this.generateBatchCode(), // 默认批次号为当年时间格式
            warehouseId: null,
            warehouseCode: null,
            warehouseName: '',
            locationId: null,
            locationCode: null,
            locationName: '',
            areaId: null,
            areaCode: null,
            areaName: '',
            expireDate: null,
            iqcCheck: 'N',
            iqcId: null,
            iqcCode: null,
            vendorId: null,
            vendorCode: null,
            vendorName: '',
            vendorBatchCode: '',
            remark: '',
            warehouseInfo: []
          };

          // 添加到本地数组
          this.itemrecptlineList.push(newLine);
          addedCount++;
        });

        // 更新总数和总金额
        this.lineTotal = this.itemrecptlineList.length;
        this.updateTotalAmount();
        // 标记数据已修改
        this.markDataModified();
        
        let message = `成功添加 ${addedCount} 个物料`;
        if (skippedCount > 0) {
          message += `，跳过 ${skippedCount} 个重复物料`;
        }
        this.$modal.msgSuccess(message);
      }
    },
    //IQC检验单选择
    handleSelectIqc() {
      this.$refs.iqcSelect.showFlag = true;
    },
    //IQC检验单选择弹出框
    onIqcSelected(obj) {
      if (obj != undefined && obj != null) {
        this.lineForm.iqcId = obj.iqcId;
        this.lineForm.iqcCode = obj.iqcCode;
      }
    },
    //供应商选择
    handleSelectVendor(row) {
      // 设置当前编辑的行
      this.currentEditRow = row;
      // 传递物料ID给供应商选择组件进行过滤
      this.$refs.vendorSelect.showFlag = true;
    },
    //供应商选择弹出框
    onVendorSelected(vendor) {
      if (vendor != undefined && vendor != null) {
        // 更新当前编辑行的供应商信息
        if (this.currentEditRow) {
          this.$set(this.currentEditRow, 'vendorId', vendor.vendorId);
          this.$set(this.currentEditRow, 'vendorCode', vendor.vendorCode);
          this.$set(this.currentEditRow, 'vendorName', vendor.vendorName);
          this.$set(this.currentEditRow, 'vendorNick', vendor.vendorNick);
          // 标记数据已修改
          this.markDataModified();
        }
        // 清空当前编辑行
        this.currentEditRow = null;
      }
    },

    // 物料创建
    handleCreateItem() {
      this.resetItemCreate();
      // 自动生成物料编码
      genCode('ITEM_CODE').then(response => {
        this.itemCreateForm.itemCode = response;
      });
      this.itemCreateOpen = true;
      this.itemCreateTitle = "创建新物料";
    },
    // 物料创建提交
    submitItemCreate() {
      this.$refs["itemCreateForm"].validate(valid => {
        if (valid) {
          addMdItem(this.itemCreateForm).then(response => {
            this.$modal.msgSuccess("物料创建成功");
            this.itemCreateOpen = false;



            this.resetItemCreate();
          }).catch(error => {
            console.error('Error creating item:', error);
            this.$modal.msgError("物料创建失败");
          });
        }
      });
    },
    // 物料分类选择变化
    handleItemTypeChange(value) {
      this.itemCreateForm.itemTypeId = value;
    },
    // 刷新主表单数据以更新总金额
    refreshMainForm() {
      const recptId = this.form.recptId;
      if (recptId) {
        getItemrecpt(recptId).then(response => {
          this.form = response.data;
          this.warehouseInfo[0] = response.data.warehouseId;
          this.warehouseInfo[1] = response.data.locationId;
          this.warehouseInfo[2] = response.data.areaId;
          // 确保总金额是最新的
          this.updateTotalAmount();
        });
      }
    },
    // 更新总金额
    updateTotalAmount() {
      try {
        let total = 0;
        this.itemrecptlineList.forEach(item => {
          if (item.amount && !isNaN(item.amount) && parseFloat(item.amount) > 0) {
            total += parseFloat(item.amount);
          }
        });
        this.form.totalAmount = total.toFixed(2);
      } catch (error) {
        this.form.totalAmount = '0.00';
      }
    },



    // 递归查找仓库
    findWarehouseById(options, warehouseId) {
      for (let option of options) {
        if (option.pId === warehouseId) {
          return option;
        }
      }
      return null;
    },

    // 递归查找库区
    findLocationById(options, warehouseId, locationId) {
      for (let warehouse of options) {
        if (warehouse.pId === warehouseId && warehouse.children) {
          for (let location of warehouse.children) {
            if (location.pId === locationId) {
              return location;
            }
          }
        }
      }
      return null;
    },

    // 递归查找库位
    findAreaById(options, warehouseId, locationId, areaId) {
      for (let warehouse of options) {
        if (warehouse.pId === warehouseId && warehouse.children) {
          for (let location of warehouse.children) {
            if (location.pId === locationId && location.children) {
              for (let area of location.children) {
                if (area.pId === areaId) {
                  return area;
                }
              }
            }
          }
        }
      }
      return null;
    },

    // 为单个明细项更新仓库名称
    updateWarehouseNamesForItem(item) {
      if (!item.warehouseId && !item.locationId && !item.areaId) {
        return;
      }

      // 查找仓库名称
      if (item.warehouseId) {
        const warehouse = this.findWarehouseById(this.warehouseOptions, item.warehouseId);
        item.warehouseName = warehouse ? warehouse.pName : '';
      }

      // 查找库区名称
      if (item.locationId) {
        const location = this.findLocationById(this.warehouseOptions, item.warehouseId, item.locationId);
        item.locationName = location ? location.pName : '';
      }

      // 查找库位名称
      if (item.areaId) {
        const area = this.findAreaById(this.warehouseOptions, item.warehouseId, item.locationId, item.areaId);
        item.areaName = area ? area.pName : '';
      }
    },

    // 行内编辑处理方法
    handleAmountChange(row) {
      // 更新总金额
      this.updateTotalAmount();
      // 标记数据已修改
      this.markDataModified();
    },

    handleSpecificationChange(row) {
      // 规格型号变更处理
      console.log('规格型号变更:', row.specification);
    },

    handleQuantityChange(row) {
      // 入库数量变更处理
      console.log('入库数量变更:', row.quantityRecived);
      // 标记数据已修改
      this.markDataModified();
    },

    handleBatchCodeFocus(row) {
      // 批次号获得焦点时，如果为空则自动填入当前时间的默认值
      if (!row.batchCode || row.batchCode.trim() === '') {
        row.batchCode = this.generateBatchCode();
        // 标记数据已修改
        this.markDataModified();
      }
    },

    handleBatchCodeChange(row) {
      // 批次号变更处理
      console.log('批次号变更:', row.batchCode);
      console.log('行数据:', row);
      
      // 如果用户清空了批次号，自动填入当前时间的默认值
      if (!row.batchCode || row.batchCode.trim() === '') {
        row.batchCode = this.generateBatchCode();
        console.log('批次号为空，自动填入默认值:', row.batchCode);
      }
      
      // 标记数据已修改
      this.markDataModified();
      
      // 检查行数据是否可编辑
      this.checkRowEditability(row);
    },



    handleWarehouseChange(row) {
      // 仓库选择变更处理
      if (row.warehouseInfo && row.warehouseInfo.length > 0) {
        row.warehouseId = row.warehouseInfo[0];
        row.locationId = row.warehouseInfo[1];
        row.areaId = row.warehouseInfo[2];
        
        // 更新仓库名称
        this.updateWarehouseNamesForItem(row);
      } else {
        row.warehouseId = null;
        row.locationId = null;
        row.areaId = null;
        row.warehouseName = '';
        row.locationName = '';
        row.areaName = '';
      }
      // 标记数据已修改
      this.markDataModified();
    },

    handleExpireDateChange(row) {
      // 有效期变更处理
      console.log('有效期变更:', row.expireDate);
      // 标记数据已修改
      this.markDataModified();
    },

    handleIqcCheckChange(row) {
      // 是否检验变更处理
      if (row.iqcCheck !== 'Y') {
        row.iqcCode = '';
        row.iqcId = null;
      }
      console.log('是否检验变更:', row.iqcCheck);
      // 标记数据已修改
      this.markDataModified();
    },

    handleIqcCodeChange(row) {
      // 检验单编号变更处理
      console.log('检验单编号变更:', row.iqcCode);
      // 标记数据已修改
      this.markDataModified();
    },

    /**
     * 判断是否为临时ID
     */
    isTemporaryId(id) {
      // null, undefined
      if (id == null) return true;

      // 字符串类型
      if (typeof id === 'string') {
        const trimmed = id.trim();
        // 以 'temp_' 开头 或 不是纯数字
        return trimmed.startsWith('temp_') || !/^\d+$/.test(trimmed);
      }

      // 数字类型
      if (typeof id === 'number') {
        // 非整数 或 小于 0
        return !Number.isInteger(id) || id < 0;
      }

      // 其他类型（如 boolean, array, object）都认为是临时的
      return true;
    },

    /**
     * 如果 item.lineId 是临时的，则清空 lineId，并删除临时标记字段
     */
    clearIdIfTemporary(item) {
      const { lineId, _isTemp, isTemp, ...rest } = item;

      // 如果是临时 ID，则不包含 lineId 字段
      if (this.isTemporaryId(lineId)) {
        return rest; // 不返回 lineId 字段
      }

      // 否则保留原始 lineId
      return { ...rest, lineId };
    },

    /**
     * 如果 item.recptId 是临时的，则清空 recptId
     */
    clearHeaderIdIfTemporary(item) {
      const { recptId, _isTemp, isTemp, ...rest } = item;

      // 如果是临时 ID，则不包含 recptId 字段
      if (this.isTemporaryId(recptId)) {
        return rest; // 不返回 recptId 字段
      }

      // 否则保留原始 recptId
      return { ...rest, recptId };
    },

    /**
     * 生成批次号 - 当年时间格式为yyyyMMdd
     */
    generateBatchCode() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      return `${year}${month}${day}`;
    },

    /**
     * 获取显示的批次号
     */
    getDisplayBatchCode(batchCode) {
      // 如果批次号为空或undefined，返回当前时间的默认值
      if (!batchCode || batchCode.trim() === '') {
        return this.generateBatchCode();
      }
      return batchCode;
    },

    /**
     * 更新列表中的数据
     */
    updateListData(updatedData) {
      if (!updatedData) return;
      
      // 查找并更新列表中的对应项
      const index = this.itemrecptList.findIndex(item => item.recptId === updatedData.recptId);
      if (index !== -1) {
        // 更新列表中的数据，确保所有字段都被更新
        const currentItem = this.itemrecptList[index];
        const updatedItem = { ...currentItem, ...updatedData };
        
        // 特别处理总金额字段
        if (this.form.totalAmount) {
          updatedItem.totalAmount = this.form.totalAmount;
        }
        
        this.$set(this.itemrecptList, index, updatedItem);
        console.log('更新列表数据:', updatedItem);
      }
    },

    /**
     * 标记数据已修改
     */
    markDataModified() {
      this.dataModified = true;
      console.log('数据已修改，当前明细数据:', this.itemrecptlineList);
    },

    /**
     * 确保数据同步完整性
     */
    ensureDataSync() {
      // 确保所有明细项的仓库名称都已更新
      this.itemrecptlineList.forEach(item => {
        if (item.warehouseId || item.locationId || item.areaId) {
          this.updateWarehouseNamesForItem(item);
        }
      });
      
      // 更新总金额
      this.updateTotalAmount();
      
      console.log('数据同步完成，当前明细数据:', this.itemrecptlineList);
    },

    /**
     * 调试方法：打印当前数据状态
     */
    debugDataState() {
      console.log('=== 数据状态调试 ===');
      console.log('当前明细列表:', this.itemrecptlineList);
      console.log('当前编辑表单:', this.lineForm);
      console.log('数据修改标记:', this.dataModified);
      console.log('总金额:', this.form.totalAmount);
      console.log('==================');
    },

    /**
     * 检查行数据是否可编辑
     */
    checkRowEditability(row) {
      console.log('=== 检查行数据可编辑性 ===');
      console.log('行数据:', row);
      console.log('optType:', this.optType);
      console.log('form.status:', this.form.status);
      console.log('是否可编辑:', this.optType != 'view' && this.form.status == 'PREPARE');
      console.log('========================');
    },

    /**
     * 验证数据同步
     */
    validateDataSync() {
      console.log('=== 验证数据同步 ===');
      console.log('明细列表长度:', this.itemrecptlineList.length);
      this.itemrecptlineList.forEach((item, index) => {
        console.log(`明细项 ${index}:`, {
          lineId: item.lineId,
          batchCode: item.batchCode,
          itemName: item.itemName
        });
      });
      console.log('==================');
    },



    /**
     * 验证物料明细中的仓库和入库数量不能为空
     */
    validateItemDetails() {
      if (!this.itemrecptlineList || this.itemrecptlineList.length === 0) {
        this.$modal.msgError("请至少添加一条物料明细");
        return false;
      }

      const errors = [];
      
      this.itemrecptlineList.forEach((item, index) => {
        const rowNumber = index + 1;
        
        // 验证仓库不能为空
        if (!item.warehouseId || !item.warehouseName || item.warehouseName.trim() === '') {
          errors.push(`第${rowNumber}行：仓库不能为空`);
        }
        
        // 验证入库数量不能为空
        if (!item.quantityRecived) {
          errors.push(`第${rowNumber}行：入库数量不能为空`);
        }
      });

      if (errors.length > 0) {
        this.$modal.msgError(errors.join('\n'));
        return false;
      }

      return true;
    },

    /**
     * 修复radio组件的无障碍访问问题
     */
    fixRadioAccessibility() {
      // 查找所有带有aria-hidden="true"的radio input元素
      const radioInputs = document.querySelectorAll('.el-radio__input[aria-hidden="true"] .el-radio__original');
      radioInputs.forEach(input => {
        // 移除tabindex属性，防止获得焦点
        input.removeAttribute('tabindex');
        // 设置pointer-events为none
        input.style.pointerEvents = 'none';
        // 确保input不可聚焦
        input.setAttribute('tabindex', '-1');
      });
    }
  }
};
</script>
<style scoped>
.collapse-title {
  flex: 0 1 54%;
  order: 1;
}

/* 修复aria-hidden无障碍访问问题 */
.el-radio__input {
  position: relative;
}

.el-radio__input[aria-hidden="true"] {
  pointer-events: none;
}

.el-radio__input[aria-hidden="true"] .el-radio__inner {
  cursor: not-allowed;
}

/* 确保disabled状态的radio组件不会产生焦点问题 */
.el-radio.is-disabled .el-radio__input {
  cursor: not-allowed;
}

.el-radio.is-disabled .el-radio__input .el-radio__inner {
  cursor: not-allowed;
}

/* 专门处理iqc-check-radio-group的无障碍访问问题 */
.iqc-check-radio-group .el-radio__input {
  position: relative;
}

.iqc-check-radio-group .el-radio__input[aria-hidden="true"] {
  pointer-events: none;
}

.iqc-check-radio-group .el-radio__input[aria-hidden="true"] .el-radio__inner {
  cursor: not-allowed;
}

/* 确保radio组件的input元素不会在aria-hidden时获得焦点 */
.iqc-check-radio-group .el-radio__input[aria-hidden="true"] .el-radio__original {
  pointer-events: none;
  tabindex: -1;
}
</style>
